package tt.dz.biz.service.cardno;

import org.apache.commons.lang3.StringUtils;
import tt.dz.common.BusinessException;
import tt.dz.common.DzConstants;
import tt.dz.common.DzConstants.CardBIN;
import tt.dz.common.DzConstants.CardType;
import tt.dz.vo.MerchantVO;

public class DefaultCardNoBuilder
  implements CardNoBuilder
{
  private CardNoSequenceGenerator sequenceGenerator;
  private DzConstants.CardType cardType;
  private DzConstants.CardBIN cardBin;
  private MerchantVO vo;
  private String areaCode;
  
  public void setCardType(DzConstants.CardType cardType)
  {
    this.cardType = cardType;
  }
  
  public void setCardBin(DzConstants.CardBIN cardBin)
  {
    this.cardBin = cardBin;
  }
  
  public void setAreaCode(String areaCode)
  {
    this.areaCode = areaCode;
  }
  
  public void setMerchant(MerchantVO vo)
  {
    this.vo = vo;
  }
  
  public void setSequenceGenerator(CardNoSequenceGenerator sequenceGenerator)
  {
    this.sequenceGenerator = sequenceGenerator;
  }
  
  public DefaultCardNoProduct[] product(int productCount)
    throws BusinessException
  {
    checkNotNull();
    String[] sequences = this.sequenceGenerator.generator(productCount);
    if (productCount != sequences.length) {
      throw new BusinessException("实际创建序号数量与期望值不一致");
    }
    DefaultCardNoProduct[] cardNoProducts = new DefaultCardNoProduct[productCount];
    DefaultCardNoProduct product = null;
    String sequence = null;
    String merchantCode = this.vo.getMerchantCode();
    String signalCode = this.vo.getSignalCode();
    for (int i = 0; i < productCount; i++)
    {
      sequence = sequences[i];
      if (StringUtils.isEmpty(sequence)) {
        throw new BusinessException("实际创建序号存在空异常");
      }
      product = new DefaultCardNoProduct();
      product.setCardBin(this.cardBin.value());
      product.setCardType(this.cardType.value());
      product.setAreaCode(this.areaCode);
      product.setSignalCode(signalCode);
      product.setSequence(sequence);
      product.createCheckCode();
      product.setMerchantCode(merchantCode);
      cardNoProducts[i] = product;
    }
    return cardNoProducts;
  }
  
  private void checkNotNull()
    throws BusinessException
  {
    if (this.cardBin == null) {
      throw new BusinessException("缺少卡bin");
    }
    if (this.areaCode == null) {
      throw new BusinessException("缺少区域码");
    }
    if (this.cardType == null) {
      throw new BusinessException("缺少类型");
    }
    if (this.vo == null) {
      throw new BusinessException("缺少运营商信息");
    }
    if (StringUtils.isEmpty(this.vo.getMerchantCode())) {
      throw new BusinessException("缺少运营商编码");
    }
    if (StringUtils.isEmpty(this.vo.getSignalCode())) {
      throw new BusinessException("缺少运营商代码");
    }
    if (this.sequenceGenerator == null) {
      throw new BusinessException("缺少sequence的创建器");
    }
  }
}
